import { type IObject, udp } from '@cscec/udp-ui';
import type { ComponentGenerator, IAmisEditorPlugin, IPackages } from './interface';
import { getSchemaTpl } from 'amis-editor';

/**
 * 定义一个amis组件
 * @param generator amis组件生成函数
 */
export function defineAmisPlugin<ComponentProps = any>(generator: ComponentGenerator<ComponentProps>) {
  return generator;
}

/**
 * 创建amis组件plugin生成器
 * @param pluginComponents
 */
export function createPluginGenerator(pluginComponents: Record<string, ComponentGenerator>) {
  return (pluginRender: Function, packages: IPackages): IAmisEditorPlugin[] => {
    const plugins: IAmisEditorPlugin[] = [];
    Object.keys(pluginComponents).forEach((key: string) => {
      const pluginComp = pluginComponents[key];
      const { component, options, pluginName } = pluginComp(packages);
      const plugin = pluginRender(component, options);
      if (plugin) {
        plugin.prototype.name = pluginName || key;
        plugins.push({
          name: options.name,
          type: options.type,
          plugin
        });
      }
    });
    return plugins;
  };
}

/**
 * forEach循环
 * @param arr
 * @param callback
 * @returns
 */
export function asyncForEach(arr: any[], callback: Function) {
  const resultList: any[] = [];
  if (!Array.isArray(arr) || !arr.length) {
    return resultList;
  }
  const len = arr.length;
  return new Promise((resolve) => {
    arr.forEach(async (item, index) => {
      const result = await callback(item, index);
      resultList.push(result);
      if (resultList.length === len) {
        resolve(resultList);
      }
    });
  });
}

/**
 * 大驼峰
 * @param str
 * @returns
 */
export function dashToCamel(str: string) {
  str = (str || '').split('_')[0];
  return udp.firstCase(str.replace(/-([a-z])/g, (_, p1) => p1.toUpperCase()));
}

/**
 * 获取自定义表单项组件的options信息
 * @param param0
 * @returns
 */
export function getBaseFormItem({
  type,
  icon,
  name,
  order,
  tpls = [],
  valueLabel = false,
  extendProps = {},
  xtype
}: {
  type: string;
  icon: string;
  name: string;
  order: number;
  tpls?: any[];
  valueLabel?: boolean;
  extendProps?: { name?: string; label?: string };
  xtype?: string;
}) {
  const scaffold: any = {
    label: name,
    name: type.replaceAll('-', ''),
    xtype,
    dragType: 'basic-field'
  };
  if (valueLabel) {
    scaffold.nameField = `${scaffold.name}EXName`;
  }
  return {
    type: `udp-${type}`,
    isFormItem: true,
    order: order,
    name,
    group: '表单项',
    icon,
    description: name,
    panelTitle: name,
    scaffold,
    panelTabs: [
      {
        title: '常规',
        body: [
          getSchemaTpl('collapseGroup', [
            {
              title: '基本',
              body: [
                getInputTpl('label', { label: '标题' }),
                getInputTpl('name', { label: '字段名', required: true, disabledOn: '!!table' }),
                valueLabel ? getInputTpl('nameField', { label: '名称字段', value: '${name}EXName' }) : null,
                getInputTpl('required', { type: 'switch', label: '必填' }),
                getInputTpl('disabled', { type: 'switch', label: '只读' }),
                getInputTpl('hidden', { type: 'switch', label: '隐藏' }),
                ...tpls,
                getExtendProps(extendProps)
              ].filter(Boolean)
            }
          ])
        ]
      },
      {
        title: '外观',
        body: [getSchemaTpl('collapseGroup', [...getSchemaTpl('theme:common', { styleName: 'style' })])]
      }
    ]
  };
}

/**
 * 获取表单公共属性
 * @param props
 * @returns
 */
export function getBaseCommonProps(props: IObject) {
  const cp = [
    'disabled',
    'hidden',
    'value',
    'onChange',
    'style',
    'helpId',
    'options',
    'multiple',
    'showTime',
    'params',
    'checkedChildren',
    'unCheckedChildren',
    'title',
    'typeCode',
    'modal',
    'loadByFocus',
    'prefix',
    'suffix',
    'showCount'
  ] as const;
  return cp.reduce(
    (p, c) => {
      if (props.hasOwnProperty(c)) {
        return { ...p, [c]: props[c] };
      }
      return p;
    },
    { ...props.extend_props }
  ) as Record<(typeof cp)[number], any>;
}

/**
 * 获取样式模板
 * @param styleName 样式属性
 * @returns
 */
export function getStyleTpl(styleName: string = 'style') {
  return [
    getSchemaTpl('theme:paddingAndMargin', {
      name: styleName
    }),
    {
      label: '边框',
      type: 'group',
      mode: 'default',
      body: [
        {
          type: 'style-border',
          name: `${styleName}`,
          mode: 'default'
        }
      ]
    },
    {
      name: `${styleName}.background`,
      label: '背景',
      mode: 'default',
      type: 'input-color',
      clearable: true,
      inputClassName: 'ae-border-colorpicker'
    }
  ];
}

/**
 * 获取文本输入模板
 * @returns
 */
export function getInputTpl(name: string, options?: { type?: string; label?: string; [x: string]: any }) {
  const { type = 'text', label, ...payload } = options || {};
  const inputType = ['textarea', 'switch', 'tree-select', 'select'].includes(type) ? type : `input-${type}`;
  const config: any = {
    mode: label ? 'horizontal' : 'default',
    type: inputType,
    name,
    label,
    ...payload
  };
  if (config.mode === 'horizontal' && config.type === 'switch' && !config.inputClassName) {
    config.inputClassName = 'is-inline';
  }
  return config;
}
/**
 * 获取静态数据源
 * @param name
 * @returns
 */
export function getOptionsTpl(name: string = 'options') {
  return {
    label: '数据源',
    mode: 'normal',
    name,
    type: 'ae-optionControl',
    className: 'udp-static-options',
    closeDefaultCheck: true // 关闭默认值设置
  };
}

/**
 * 获取扩展数据模板
 * @param props
 * @returns
 */
export function getExtendProps(props: { name?: string; label?: string } = {}) {
  return {
    type: 'input-kv',
    name: 'extend_props',
    label: '扩展属性',
    ...props
  };
}

/**
 *
 * @param name 获取接口模板
 * @param options
 * @returns
 */
export function getApiTpl(name: string = 'source', options?: { title?: string; data?: object; [x: string]: any }) {
  return {
    title: options?.title || '数据源',
    body: [
      getSchemaTpl('apiControl', {
        name,
        mode: 'row',
        labelClassName: 'none',
        data: options?.data || {
          code: 0,
          data: {
            list: [
              {
                title: '标题',
                type: '类型',
                creator: '创建人',
                createtime: '创建时间',
                remark: '备注（部门信息）',
                link: '跳转链接',
                routeName: '微前端路由'
              }
            ],
            pageNum: 1,
            pageSize: 8,
            total: 0
          },
          message: ''
        }
      })
    ]
  };
}
/**
 *获取多个接口模板
 * @param title
 * @param options
 * @returns
 */
interface ApiTpl {
  name: string;
  data?: object;
  [x: string]: any;
}
export function getApiTpls(title: string = '数据源', options: ApiTpl[]) {
  return {
    title,
    body: options?.map((e: ApiTpl) => {
      return getSchemaTpl('apiControl', {
        label: e?.label,
        name: e.name,
        mode: 'row',
        labelClassName: 'none',
        data: e?.data || {
          code: 0,
          data: {
            list: [
              {
                title: '标题',
                type: '类型',
                creator: '创建人',
                createtime: '创建时间',
                remark: '备注（部门信息）',
                link: '跳转链接',
                routeName: '微前端路由'
              }
            ],
            pageNum: 1,
            pageSize: 8,
            total: 0
          },
          message: ''
        }
      });
    })
  };
}
